package com.baizhi.common;

import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

//声明全局异常类
@RestControllerAdvice
public class BaseExceptionHandler {


    @ExceptionHandler(BindException.class)
    public R getBindException(BindException e){
        Map map=new HashMap();
        List<FieldError> fieldErrors = e.getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            //获取当前校验的属性
            String field = fieldError.getField();
            //获取校验错误信息
            String defaultMessage = fieldError.getDefaultMessage();
            map.put(field,defaultMessage);
        }
        return R.error().put("data",map);
    }

    @ExceptionHandler(InternalAuthenticationServiceException.class)
    public R getInternalAuthenticationServiceException(InternalAuthenticationServiceException e){
        System.out.println("=============");
        return R.error(e.getMessage());
    }
    @ExceptionHandler(CodeException.class)
    public R getCodeException(CodeException e){
        return R.error(e.getMessage());
    }


   /* @ExceptionHandler(RuntimeException.class)
    public R getRuntimeException(RuntimeException e){
        return R.error(e.getMessage());
    }*/

}
